package com.guessdroid.sensing;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder.AudioSource;
import android.net.wifi.WifiManager;
import android.os.PowerManager;


// initialization and storage of boring details
public class Keeper {
	public PowerManager mPowerManager;
	public PowerManager.WakeLock mWakeLock;
	public WifiManager mWifiManager;
	public SensorManager mSensorManager;
	public Sensor mLight;
	public Sensor mAcc;
	public AudioRecord micBuffer=null;
	public int audioBufferSizeInBytes;

	public Keeper(Activity activity, Context context){
		mPowerManager = (PowerManager)activity.getSystemService(Context.POWER_SERVICE);
		mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
        mSensorManager = (SensorManager)activity.getSystemService(Context.SENSOR_SERVICE);
        mLight = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
        mAcc = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mWifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
        // these may be null if not found.. we use them so it is ok to crash because of that

        audioBufferSizeInBytes = 2*4410*2;  // 200ms delays possible?
        // "read() blocks until the buffer is full" -random (google?) developer
        // by default all parts run in the same thread
        // minbuffersize IIRC 4096B, ..does it have to divide this..?
        resetAudio();
	}
	
    // "Data should be read from the audio hardware in chunks of sizes
    // inferior to the total recording buffer size" -API
	//
	// possibilities:
	// 1. offset in read is automatically 0 for first non-read sample.
	// 2. we have to keep calculating offset manually and it uses modulo addition automatically.
	// 3. we have to keep calculating offset and length to end-of-buffer manually.
	// 4. manual offset, but we can read entire buffer. overflow risk
	// ?. other random thought-provoking ideas
	public int aReadSize() // in 2*bytes
	{
		return audioBufferSizeInBytes/4;
	}
	
	public void resetAudio()
	{
		releaseAudio();
        micBuffer = new AudioRecord(AudioSource.MIC,
				44100,
				AudioFormat.CHANNEL_IN_MONO,
				AudioFormat.ENCODING_PCM_16BIT,
				audioBufferSizeInBytes);
	}
	
	public void releaseAudio()
	{
		if (micBuffer!=null) {micBuffer.release();micBuffer=null;}
	}
}
